package com.voa.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.hibernate.SQLQuery;
import org.hibernate.SessionFactory;
import org.hibernate.type.StandardBasicTypes;
import org.team4.dao.GenericDAO;
import org.team4.domain.Users;
import org.team4.exception.CRUDException;

import com.voa.domain.Blog;
import com.voa.vo.BlogAgg;

/**
 * <p>程序名称：       BlogDAO.java</p>
 * <p>程序说明：       日志DAO</p>
 * <p>版权信息：       Copyright 深圳市维远泰克科技有限公司</p>
 * <p>时间：          Feb 11, 2011 11:32:55 AM</p>	
 * 
 * @author：          Marker.King
 * @version：         Ver 0.1
 */
public class BlogDAO extends GenericDAO<Blog> {

	private static final long serialVersionUID = 3727796859494457745L;
	private static BlogDAO instance;
	
	public static BlogDAO getInstance(SessionFactory sessionFactory) {
        if(instance == null) {
            instance =  new BlogDAO(sessionFactory);
        }
        return instance;
    }

	private BlogDAO(SessionFactory sessionFactory) {
		super(sessionFactory, Blog.class);
	}
	
	/**
	 * 查找日志，以聚合方式返回
	 * @param where
	 * @return
	 * @throws CRUDException
	 */
	public List<BlogAgg> findBlogAggregation(String where) throws CRUDException {
		List<BlogAgg> blogAggList = new ArrayList<BlogAgg>();
		StringBuffer sql = new StringBuffer();
		sql.append("select count(id) as m, forDate as fd,creator as c from Blog where 1=1 ");
		sql.append(where);
		sql.append(" group by forDate, creator order by forDate desc");
		SQLQuery query = this.getSession().createSQLQuery(sql.toString());
		query.addScalar("m", StandardBasicTypes.LONG);
		query.addScalar("fd", StandardBasicTypes.DATE);
		query.addScalar("c", StandardBasicTypes.STRING);
		List list = query.list();
		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			Object[] row = (Object[]) iterator.next();
			BlogAgg blogAgg = new BlogAgg();
			blogAgg.setCount((Long) row[0]);
			blogAgg.setForDate((Date) row[1]);
			blogAgg.setCreator((Users) this.getSession().get(Users.class, (String)row[2]));
			blogAggList.add(blogAgg);
		}
		return blogAggList;
	}

}
